package beliberda;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.*;

import com.google.appengine.api.users.User;

import account.AccountDAO;

//import com.google.appengine.api.users.User;

@SuppressWarnings("serial")
public abstract class AbstractHistoryServlet extends HttpServlet {

	private static final Logger log = Logger.getLogger(AbstractHistoryServlet.class.getName());
	    protected abstract void showForm(HttpServletRequest req, 
		    HttpServletResponse resp) throws ServletException, IOException;

		protected abstract void handleSubmit(HttpServletRequest req, 
		    HttpServletResponse resp) throws ServletException, IOException;
		
		protected abstract void showHistories(String nick, HttpServletRequest req, 
		    HttpServletResponse resp) throws ServletException, IOException;
		
		protected abstract void createHistory(String nick, HttpServletRequest req, 
			    HttpServletResponse resp) throws ServletException, IOException;
		
		protected abstract void showHistory(long id, HttpServletRequest req, 
			    HttpServletResponse resp) throws ServletException, IOException;
		
		private AccountDAO dao = new AccountDAO();
		
		@Override
		protected void doGet(HttpServletRequest req, HttpServletResponse resp)
		    throws ServletException, IOException {
				
			HttpSession session = req.getSession(true);
			User user = (User) session.getAttribute("user");
			
			String nick="";
		    String action = req.getParameter("action");
		    
		    if ("history".equals(action)){
		    	nick = req.getParameter("nick");
		        showHistories(nick, req, resp);}
		    else{ 
		    	  try{
		    		 nick = dao.getByAddr(user.getEmail()).getNick();
		    	     }
		    	  catch(Exception ex){log.warning(ex.getMessage());}	    
		    if(nick.equals(""))showForm(req, resp); else showHistories(nick, req, resp);       
		    }
		    if ("read".equals(action)) {
		    	long id = Long.parseLong(req.getParameter("id").replace("_", ""));
		        showHistory(id, req, resp);}
		    if ("create".equals(action)) {
		    	nick = req.getParameter("nick");
		    createHistory(nick, req, resp);}	        
		}

		@Override
		protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
		    throws ServletException, IOException {
			handleSubmit(req, resp);
		}
}
